#!/bin/sh
# PCP QA Test No. 1321
# Test pmlogger dynamic PMNS support

seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.openmetrics

_pmdaopenmetrics_check || _notrun "openmetrics pmda not installed"

status=1	# failure is the default!

_cleanup()
{
    $sudo $PCP_BINADM_DIR/pmsignal -s TERM $pmlogger_pid >/dev/null 2>&1
    $sudo rm -fr $tmp.datadir

    _wait_pmlogger_end $pmlogger_pid
    _pmdaopenmetrics_cleanup
    rm -rf $tmp.*
}

_prepare_pmda openmetrics
trap "_cleanup; exit \$status" 0 1 2 3 15
_stop_auto_restart pmcd

_createURL()
{
    SRC=$1
    NMET=$2

    [ ! -d $tmp.datadir ] && mkdir -p $tmp.datadir

    _txt=$tmp.datadir/source$SRC.txt
    for j in $(seq 1 $NMET); do
	echo "# HELP metric$j local test metric" >>$_txt
	echo "# Type metric$j gauge" >>$_txt
	echo "metric$j {somelabel=\"somevalue\"} 0.0" >>$_txt
    done

    _url="$CONFIG_DIR/source$SRC.url"
    echo "file://$tmp.datadir/source$SRC.txt" >$_url
    echo;echo == Created URL file $_url
    # echo;echo == curl URL returns
    # curl -G -s `cat $_url` || exit 1
}

_pmdaopenmetrics_save_config
_pmdaopenmetrics_install
_pmdaopenmetrics_wait_for_metric openmetrics.control.calls
pminfo openmetrics >/dev/null && echo ... pmda install succeeded

# start up pmlogger
echo 'log mandatory on default { openmetrics }' >$tmp.pmlogger.config

echo;echo === pmlogger config ===
cat $tmp.pmlogger.config

rm -f $tmp.dynamic.*
pmlogger -t 500msec -l $tmp.pmlogger.log -c $tmp.pmlogger.config $tmp.dynamic &
pmlogger_pid=$!

for n in `seq 1 4`; do
	# while pmlogger is fetching every 500msec, we create a new URL every 2s.
	sleep 2
	_createURL $n $n
	echo;echo === openmetrics live PMNS is now ===
	pminfo openmetrics | LC_COLLATE=POSIX sort
done

# When new dynamic metrics are detected, the _next_ fetch will fetch them.
# So wait for a bit so pmlogger has a chance to fetch the new metrics.
sleep 2

# now kill pmlogger and check the new metrics appeared dynamically
$sudo $PCP_BINADM_DIR/pmsignal -s TERM $pmlogger_pid >/dev/null 2>&1

echo;echo === resulting archive contains the following openmetrics metrics ===
pminfo -a $tmp.dynamic openmetrics | LC_COLLATE=POSIX sort
# rm -rf /tmp/saved; mkdir -p /tmp/saved; cp $tmp.dynamic.* $PCP_LOG_DIR/pmcd/openmetrics.log* $tmp.pmlogger.log /tmp/saved

echo === openmetrics.log === >> $seq_full
cat $PCP_LOG_DIR/pmcd/openmetrics.log >> $seq_full

echo === pmlogger.log === >> $seq_full
cat $tmp.pmlogger.log >> $seq_full

_pmdaopenmetrics_remove

# success, all done
status=0
exit
